import React, { useState, useRef, useEffect } from "react";
import {
  Form,
  Input,
  Button,
  Checkbox,
  Card,
  message,
  Space,
  Divider,
  Alert,
  Spin,
  Row,
  Col,
} from "antd";
import {
  UserOutlined,
  LockOutlined,
  SafetyOutlined,
  EyeInvisibleOutlined,
  EyeTwoTone,
  LoginOutlined,
  MobileOutlined,
  MailOutlined,
} from "@ant-design/icons";
import { Link, useNavigate } from "react-router-dom";
import styled, { keyframes } from "styled-components";

// 动画定义
const fadeInUp = keyframes`
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
`;

const float = keyframes`
  0%, 100% { transform: translateY(0px); }
  50% { transform: translateY(-10px); }
`;

const gradient = keyframes`
  0% { background-position: 0% 50%; }
  50% { background-position: 100% 50%; }
  100% { background-position: 0% 50%; }
`;

// 样式组件
const LoginContainer = styled.div`
  min-height: 100vh;
  background: linear-gradient(-45deg, #667eea, #764ba2, #f093fb, #f5576c);
  background-size: 400% 400%;
  animation: ${gradient} 15s ease infinite;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  position: relative;
  overflow: hidden;

  &::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background:
      radial-gradient(
        circle at 20% 80%,
        rgba(120, 119, 198, 0.3) 0%,
        transparent 50%
      ),
      radial-gradient(
        circle at 80% 20%,
        rgba(255, 119, 198, 0.3) 0%,
        transparent 50%
      ),
      radial-gradient(
        circle at 40% 40%,
        rgba(120, 219, 255, 0.2) 0%,
        transparent 50%
      );
  }
`;

const LoginCard = styled(Card)`
  width: 100%;
  max-width: 450px;
  border-radius: 20px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  background: rgba(255, 255, 255, 0.95);
  border: 1px solid rgba(255, 255, 255, 0.2);
  animation: ${fadeInUp} 0.8s ease-out;
  position: relative;
  z-index: 1;

  .ant-card-body {
    padding: 40px;
  }

  &::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    border-radius: 20px;
    background: linear-gradient(
      135deg,
      rgba(255, 255, 255, 0.1),
      rgba(255, 255, 255, 0.05)
    );
    pointer-events: none;
  }
`;

const Logo = styled.div`
  text-align: center;
  margin-bottom: 40px;

  .logo-icon {
    font-size: 64px;
    color: #667eea;
    margin-bottom: 16px;
    animation: ${float} 3s ease-in-out infinite;
  }

  .logo-text {
    font-size: 28px;
    font-weight: bold;
    background: linear-gradient(135deg, #667eea, #764ba2);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
    margin-bottom: 8px;
  }

  .logo-subtitle {
    color: #999;
    font-size: 14px;
  }
`;

const StyledForm = styled(Form)`
  .ant-form-item {
    margin-bottom: 24px;
  }

  .ant-input-affix-wrapper {
    border-radius: 12px;
    border: 2px solid #f0f0f0;
    transition: all 0.3s ease;
    padding: 12px 16px;
    height: auto;

    &:hover {
      border-color: #667eea;
      box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
    }

    &.ant-input-affix-wrapper-focused {
      border-color: #667eea;
      box-shadow: 0 6px 20px rgba(102, 126, 234, 0.25);
    }
  }

  .ant-input {
    border: none;
    box-shadow: none;
    font-size: 16px;

    &:focus {
      box-shadow: none;
    }
  }
`;

const LoginButton = styled(Button)`
  width: 100%;
  height: 50px;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
  background: linear-gradient(135deg, #667eea, #764ba2);
  border: none;
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 12px 30px rgba(102, 126, 234, 0.4);
    background: linear-gradient(135deg, #5a6fd8, #6a42a0);
  }

  &:active {
    transform: translateY(0);
  }

  &:disabled {
    background: #ccc;
    transform: none;
    box-shadow: none;
  }
`;

const CaptchaContainer = styled.div`
  display: flex;
  gap: 12px;
  align-items: center;
`;

const CaptchaImage = styled.div<{ backgroundImage: string }>`
  width: 120px;
  height: 40px;
  background-image: url(${(props) => props.backgroundImage});
  background-size: cover;
  background-position: center;
  border-radius: 8px;
  border: 2px solid #f0f0f0;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;

  &:hover {
    border-color: #667eea;
    transform: scale(1.05);
  }

  &::after {
    content: "点击刷新";
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0, 0, 0, 0.7);
    color: white;
    font-size: 10px;
    text-align: center;
    padding: 2px;
    opacity: 0;
    transition: opacity 0.3s ease;
  }

  &:hover::after {
    opacity: 1;
  }
`;

const SliderCaptcha = styled.div`
  width: 100%;
  height: 40px;
  background: #f5f5f5;
  border-radius: 20px;
  position: relative;
  overflow: hidden;
  border: 2px solid #f0f0f0;
  transition: border-color 0.3s ease;

  &.success {
    border-color: #52c41a;
    background: #f6ffed;
  }

  &.error {
    border-color: #ff4d4f;
    background: #fff2f0;
  }
`;

const SliderButton = styled.div<{ position: number; dragging: boolean }>`
  position: absolute;
  left: ${(props) => props.position}px;
  top: 2px;
  width: 36px;
  height: 36px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  border-radius: 50%;
  cursor: ${(props) => (props.dragging ? "grabbing" : "grab")};
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  transition: ${(props) => (props.dragging ? "none" : "all 0.3s ease")};
  user-select: none;

  &:hover {
    transform: scale(1.1);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  }
`;

const SliderTrack = styled.div<{ progress: number }>`
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  width: ${(props) => props.progress}%;
  background: linear-gradient(90deg, #667eea, #764ba2);
  border-radius: 20px;
  transition: width 0.3s ease;
  opacity: 0.3;
`;

const SliderText = styled.div`
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  color: #999;
  font-size: 14px;
  pointer-events: none;
  user-select: none;
`;

// 验证码接口
interface CaptchaState {
  imageUrl: string;
  sliderPosition: number;
  sliderSuccess: boolean;
  sliderDragging: boolean;
  refreshKey: number;
}

const Login: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [loginType, setLoginType] = useState<"account" | "phone">("account");
  const navigate = useNavigate();
  const sliderRef = useRef<HTMLDivElement>(null);

  // 验证码状态
  const [captcha, setCaptcha] = useState<CaptchaState>({
    imageUrl: "",
    sliderPosition: 0,
    sliderSuccess: false,
    sliderDragging: false,
    refreshKey: 0,
  });

  // 生成图像验证码
  const generateImageCaptcha = () => {
    // 模拟生成验证码图片
    const canvas = document.createElement("canvas");
    canvas.width = 120;
    canvas.height = 40;
    const ctx = canvas.getContext("2d");

    if (ctx) {
      // 背景渐变
      const gradient = ctx.createLinearGradient(0, 0, 120, 40);
      gradient.addColorStop(0, "#667eea");
      gradient.addColorStop(1, "#764ba2");
      ctx.fillStyle = gradient;
      ctx.fillRect(0, 0, 120, 40);

      // 随机验证码文字
      const chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
      let code = "";
      for (let i = 0; i < 4; i++) {
        code += chars.charAt(Math.floor(Math.random() * chars.length));
      }

      ctx.fillStyle = "white";
      ctx.font = "bold 20px Arial";
      ctx.textAlign = "center";
      ctx.fillText(code, 60, 28);

      // 添加干扰线
      for (let i = 0; i < 5; i++) {
        ctx.beginPath();
        ctx.moveTo(Math.random() * 120, Math.random() * 40);
        ctx.lineTo(Math.random() * 120, Math.random() * 40);
        ctx.strokeStyle = "rgba(255, 255, 255, 0.5)";
        ctx.stroke();
      }
    }

    return canvas.toDataURL();
  };

  // 初始化验证码
  useEffect(() => {
    setCaptcha((prev) => ({
      ...prev,
      imageUrl: generateImageCaptcha(),
    }));
  }, []);

  // 刷新验证码
  const refreshCaptcha = () => {
    setCaptcha((prev) => ({
      ...prev,
      imageUrl: generateImageCaptcha(),
      refreshKey: prev.refreshKey + 1,
      sliderPosition: 0,
      sliderSuccess: false,
    }));
  };

  // 滑块验证逻辑
  const handleSliderMouseDown = (e: React.MouseEvent) => {
    if (captcha.sliderSuccess) return;

    setCaptcha((prev) => ({ ...prev, sliderDragging: true }));

    const startX = e.clientX;
    const startPosition = captcha.sliderPosition;
    const sliderWidth = sliderRef.current?.offsetWidth || 300;
    const buttonWidth = 36;
    const maxPosition = sliderWidth - buttonWidth - 4;

    const handleMouseMove = (e: MouseEvent) => {
      const deltaX = e.clientX - startX;
      const newPosition = Math.max(
        0,
        Math.min(startPosition + deltaX, maxPosition)
      );

      setCaptcha((prev) => ({ ...prev, sliderPosition: newPosition }));

      // 检查是否滑动到终点
      if (newPosition >= maxPosition * 0.95) {
        setCaptcha((prev) => ({
          ...prev,
          sliderSuccess: true,
          sliderDragging: false,
          sliderPosition: maxPosition,
        }));
        document.removeEventListener("mousemove", handleMouseMove);
        document.removeEventListener("mouseup", handleMouseUp);
        message.success("验证成功！");
      }
    };

    const handleMouseUp = () => {
      setCaptcha((prev) => ({ ...prev, sliderDragging: false }));
      document.removeEventListener("mousemove", handleMouseMove);
      document.removeEventListener("mouseup", handleMouseUp);

      // 如果没有成功，重置位置
      if (!captcha.sliderSuccess) {
        setTimeout(() => {
          setCaptcha((prev) => ({ ...prev, sliderPosition: 0 }));
        }, 500);
      }
    };

    document.addEventListener("mousemove", handleMouseMove);
    document.addEventListener("mouseup", handleMouseUp);
  };

  // 登录处理
  const handleLogin = async (values: any) => {
    if (!captcha.sliderSuccess) {
      message.error("请先完成滑块验证");
      return;
    }

    setLoading(true);
    try {
      // 模拟登录API调用
      await new Promise((resolve) => setTimeout(resolve, 2000));

      message.success("登录成功！");

      // 模拟根据角色跳转
      const userRole = values.username.startsWith("admin")
        ? "admin"
        : values.username.startsWith("teacher")
          ? "teacher"
          : "student";

      navigate(`/${userRole}`);
    } catch (error) {
      message.error("登录失败，请检查用户名和密码");
    } finally {
      setLoading(false);
    }
  };

  return (
    <LoginContainer>
      <LoginCard>
        <Logo>
          <div className="logo-icon">🎓</div>
          <div className="logo-text">XHT教学平台</div>
          <div className="logo-subtitle">智能化教学管理系统</div>
        </Logo>

        <StyledForm
          form={form}
          name="login"
          onFinish={handleLogin}
          size="large"
          requiredMark={false}
        >
          {/* 登录方式切换 */}
          <div style={{ textAlign: "center", marginBottom: 24 }}>
            <Space size="large">
              <Button
                type={loginType === "account" ? "primary" : "text"}
                icon={<UserOutlined />}
                onClick={() => setLoginType("account")}
              >
                账号登录
              </Button>
              <Button
                type={loginType === "phone" ? "primary" : "text"}
                icon={<MobileOutlined />}
                onClick={() => setLoginType("phone")}
              >
                手机登录
              </Button>
            </Space>
          </div>

          {loginType === "account" ? (
            <>
              <Form.Item
                name="username"
                rules={[{ required: true, message: "请输入用户名或邮箱" }]}
              >
                <Input
                  prefix={<UserOutlined />}
                  placeholder="用户名 / 邮箱"
                  autoComplete="username"
                />
              </Form.Item>

              <Form.Item
                name="password"
                rules={[{ required: true, message: "请输入密码" }]}
              >
                <Input.Password
                  prefix={<LockOutlined />}
                  placeholder="密码"
                  autoComplete="current-password"
                  iconRender={(visible) =>
                    visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />
                  }
                />
              </Form.Item>
            </>
          ) : (
            <>
              <Form.Item
                name="phone"
                rules={[
                  { required: true, message: "请输入手机号" },
                  { pattern: /^1\d{10}$/, message: "请输入正确的手机号" },
                ]}
              >
                <Input
                  prefix={<MobileOutlined />}
                  placeholder="手机号"
                  autoComplete="tel"
                />
              </Form.Item>

              <Form.Item
                name="smsCode"
                rules={[{ required: true, message: "请输入验证码" }]}
              >
                <Row gutter={8}>
                  <Col span={16}>
                    <Input
                      prefix={<SafetyOutlined />}
                      placeholder="短信验证码"
                    />
                  </Col>
                  <Col span={8}>
                    <Button style={{ width: "100%" }}>获取验证码</Button>
                  </Col>
                </Row>
              </Form.Item>
            </>
          )}

          {/* 图像验证码 */}
          <Form.Item
            name="captcha"
            rules={[{ required: true, message: "请输入图像验证码" }]}
          >
            <CaptchaContainer>
              <Input
                prefix={<SafetyOutlined />}
                placeholder="验证码"
                style={{ flex: 1 }}
              />
              <CaptchaImage
                backgroundImage={captcha.imageUrl}
                onClick={refreshCaptcha}
              />
            </CaptchaContainer>
          </Form.Item>

          {/* 滑块验证 */}
          <Form.Item>
            <div style={{ marginBottom: 8, color: "#666", fontSize: 14 }}>
              安全验证
            </div>
            <SliderCaptcha
              ref={sliderRef}
              className={captcha.sliderSuccess ? "success" : ""}
            >
              <SliderTrack
                progress={(captcha.sliderPosition / (300 - 40)) * 100}
              />
              <SliderText>
                {captcha.sliderSuccess ? "验证成功" : "向右滑动验证"}
              </SliderText>
              <SliderButton
                position={captcha.sliderPosition}
                dragging={captcha.sliderDragging}
                onMouseDown={handleSliderMouseDown}
              >
                {captcha.sliderSuccess ? "✓" : "→"}
              </SliderButton>
            </SliderCaptcha>
          </Form.Item>

          {/* 记住我和忘记密码 */}
          <Form.Item>
            <div
              style={{
                display: "flex",
                justifyContent: "space-between",
                alignItems: "center",
              }}
            >
              <Form.Item name="remember" valuePropName="checked" noStyle>
                <Checkbox>记住我</Checkbox>
              </Form.Item>
              <Link to="/forgot-password" style={{ color: "#667eea" }}>
                忘记密码？
              </Link>
            </div>
          </Form.Item>

          {/* 登录按钮 */}
          <Form.Item>
            <LoginButton
              type="primary"
              htmlType="submit"
              loading={loading}
              icon={<LoginOutlined />}
              disabled={!captcha.sliderSuccess}
            >
              {loading ? "登录中..." : "登录"}
            </LoginButton>
          </Form.Item>

          <Divider>
            <span style={{ color: "#999", fontSize: 14 }}>其他登录方式</span>
          </Divider>

          {/* 第三方登录 */}
          <div style={{ textAlign: "center" }}>
            <Space size="large">
              <Button
                shape="circle"
                icon="🔐"
                size="large"
                style={{ backgroundColor: "#1677ff" }}
              />
              <Button
                shape="circle"
                icon="📱"
                size="large"
                style={{ backgroundColor: "#52c41a" }}
              />
              <Button
                shape="circle"
                icon="📧"
                size="large"
                style={{ backgroundColor: "#fa8c16" }}
              />
            </Space>
          </div>

          {/* 注册链接 */}
          <div style={{ textAlign: "center", marginTop: 24 }}>
            <span style={{ color: "#999" }}>还没有账号？</span>
            <Link to="/register" style={{ color: "#667eea", marginLeft: 8 }}>
              立即注册
            </Link>
          </div>
        </StyledForm>
      </LoginCard>
    </LoginContainer>
  );
};

export default Login;
